<!DOCTYPE html>
<html lang="en-us" id="extr-page">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" media="screen"
	href="../../global/css/bootstrap.min.css">
<link rel="stylesheet"
	href="../../global/css/ztree/zTreeStyle/zTreeStyle.css" type="text/css">
<link rel="stylesheet" href="../../global/css/ztree/demo.css"
	type="text/css">
</head>
<body>
	<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
		<form class="form-horizontal" onsubmit="return false" id="form"
			enctype="multipart/form-data">
			<fieldset>
				<input type="hidden" id="formworkId" name="formworkId">
            <div class="form-group">
                <label class="col-md-2 control-label">模板名称</label>
                <div class="col-md-10">
                    <input class="form-control" placeholder="品牌名称" type="text" name="formworkName" id="formworkName"
                           data-bv-notempty="true"
                           data-bv-notempty-message="模板名称不能为空">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-2 control-label">模板类型</label>
                <div class="col-md-10">
                    <select class="form-control" onchange=typeChange() id="formworkType" name="formworkType">
                    	<option value="">请选择</option>
                    	<option value="1">买家承担运费</option>
                    	<option value="2">卖家包邮</option>
                    </select>
                </div>
            </div>
            <div id="priceTypediv" class="form-group">
                <label class="col-md-2 control-label">计价方式</label>
                <div class="col-md-10">
                    <select class="form-control" id="priceType" name="priceType" onchange=priceChange()>
                    	<option value="">请选择</option>
                    	<option value="1">按件计</option>
                    	<option value="2">按重量计</option>
                    </select>
                </div>
            </div>
             <div id="formworkdiv" class="form-group">
                <label class="col-md-2 control-label">运费模板</label>
                <div class="col-md-10" id="col-md-10">
                    <input type="text" readonly style="border:none;text-align:center;text-align:center" value="可配送区域" name="specDetail" /><input type="hidden" readonly style="border:none;text-align:center;text-align:center" value="可配送区域ID" name="specsDetail" /><input type="text" readonly style="border:none;text-align:center" value="首件（个）" id="specNum" /><input type="text" readonly style="border:none;text-align:center" value="运费（元）" id="specPriceOld" /><input type="text" readonly style="border:none;text-align:center" value="续件（个）" id="specPriceNew" /><input type="text"  readonly style="border:none;text-align:center" value="运费（元）" name="specYj" /><input type="button" class="addSpec" value="新增规格" />
                </div>
            </div>

            <div class="form-actions">
                <div class="row" align="center">
                    <div class="col-md-12">
                        <button class="btn btn-primary" onclick="location.href='feeList.html'">返回</button>
                        <button class="btn btn-primary" type="submit" onclick="add()">
                            <i class="fa fa-save"></i> 保存
                        </button>
                    </div>
                </div>
            </div>
            
            <div style="padding-top: 10px; display: none; text-align: left" id="areaShow">
            <div class="col-md-10">
                    <ul id="treeDemo" class="ztree"></ul>
                    </div>
            </div>
			</fieldset>
		</form>
	</div>

	<script type="text/javascript"
		src="../../global/js/libs/jquery-2.1.1.min.js"></script>
	<script type="text/javascript" src="../../global/js/jq.js"></script>
	<script type="text/javascript"
		src="../../global/js/plugin/bootstrapvalidator/bootstrapValidator.min.js"></script>
	<script type="text/javascript" src="../../global/js/common.js"></script>
	<script type="text/javascript" src="../../global/layui/layui.js"></script>
	<script type="text/javascript" src="../../global/js/ajaxfileupload.js"></script>
	<script type="text/javascript" src="../../global/js/libs/jquery.ztree.all-3.5.min.js"></script>
	<script type="text/javascript">
	layui.use(['layer', 'laydate'], function () {
        var layer = layui.layer;
        var laydate = layui.laydate;
    });
	$.fn.zTree.init($("#treeDemo"), getSettting(), getMenuTree());
	function getMenuTree() {
	    var root = {
	        id: 0,
	        name: "全国",
	        open: true,
	    };

	    $.ajax({
	        type: 'get',
	        url: '/clyjFeeFormwork/getAllArea',
	        contentType: "application/json; charset=utf-8",
	        async: false,
	        success: function (data) {
	            var length = data.length;
	            var children = [];
	            for (var i = 0; i < length; i++) {
	                var d = data[i];
	                var node = createNode(d);
	                children[i] = node;
	            }

	            root.children = children;
	        }
	    });

	    return root;
	}
	//回显
	function initMenuCheck(ids) {
	    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	    var length = ids.length;
	    if (length > 0) {
	        var node = treeObj.getNodeByParam("id", 0, null);
	        treeObj.checkNode(node, true, false);
	    }

	    for (var i = 0; i < length; i++) {
	        var node = treeObj.getNodeByParam("id", ids[i], null);
	        treeObj.checkNode(node, true, false);
	    }

	}
	//获取选中的ids
	function getCheckedMenuIds() {
	    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	    var nodes = treeObj.getCheckedNodes(true);

	    var length = nodes.length;
	    var ids = [];
	    for (var i = 0; i < length; i++) {
	        var n = nodes[i];
	        var id = n['id'];
	        if(i!=0)
	        	ids.push(id);
	    }

	    return ids;
	}
	//获取选中的ids
	function getCheckedMenuNames() {
	    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	    var nodes = treeObj.getCheckedNodes(true);

	    var length = nodes.length;
	    var ids = [];
	    for (var i = 0; i < length; i++) {
	        var n = nodes[i];
	        var id = n['name'];
	        if(i!=0)
	        	ids.push(id);
	    }

	    return ids;
	}
	function createNode(d) {
	    var id = d['id'];
	    var pId = d['parentId'];
	    var name = d['addressName'];
	    var child = d['child'];

	    var node = {
	        open: false,
	        id: id,
	        name: name,
	        pId: pId,
	    };

	    if (child != null) {
	        var length = child.length;
	        if (length > 0) {
	            var children = [];
	            for (var i = 0; i < length; i++) {
	                children[i] = createNode(child[i]);
	            }

	            node.children = children;
	        }

	    }
	    return node;
	}
	function getSettting() {
	    var setting = {
	        check: {
	            enable: true,
	            chkboxType: {
	                "Y": "ps",
	                "N": "ps"
	            }
	        },
	        async: {
	            enable: true,
	        },
	        data: {
	            simpleData: {
	                enable: true,
	                idKey: "id",
	                pIdKey: "parentId",
	                rootPId: 0
	            }
	        },
	        callback: {
	            onCheck: zTreeOnCheck
	        }
	    };

	    return setting;
	}
	function zTreeOnCheck(event, treeId, treeNode) {
	}
	
	
	
	
	
	
	
		initData();
		function initData() {
			var formworkId= getUrlParam("formworkId");
			if(formworkId!=null && formworkId!="null" && formworkId!=""){
				//数据回显
				$.ajax({
	                type: 'get',
	                url: '/clyjFeeFormwork/' + formworkId,
	                async: false,
	                success: function (data) {
	                    $("#formworkName").val(data.formworkName);
	                    $("#formworkId").val(data.formworkId);
	                    $("#formworkType").val(data.formworkType);
	                    $("#priceType").val(data.priceType);
	                    var list = data.detailList;
	                    console.info(list)
	                    if(list==null || list.length==0)
	                    	return;
	                    for(var i=0;i<list.length;i++){
	                    		$("#col-md-10").append('<br/><div><input type="text" class="areaShow"  value="'+list[i].detailArea+'" name="detailArea" /><input type="hidden"  value="'+list[i].areaId+'" name="AreaId" /><input type="text"  value="'+list[i].firstNum+'" name="firstNum" /><input type="text"  value="'+list[i].firstPrice+'" name="firstPrice" /><input type="text"  value="'+list[i].nextNum+'" name="nextNum" /><input type="text"  value="'+list[i].nextPrice+'" name="nextPrice" /><button class="delSpec">删除模板</button></div>');
	                    }
	                }
	            });
				
			}
		}
		

		$('#form').bootstrapValidator();

		//新增模板
		function add() {
			var bootstrapValidator = $("#form").data('bootstrapValidator');
			bootstrapValidator.validate();
			if (!bootstrapValidator.isValid()) {
				return;
			}
			$("form").ajaxSubmit({
				type : 'post',
				url : '/clyjFeeFormwork/saveFee',
				traditional : true,
				contentType : "application/json; charset=utf-8",
				success : function(data) {
					if(data.code=="success"){
						layer.msg("保存成功", {
							shift : -1,
							time : 1000
						}, function() {
							location.href = "feeList.html";
						});
					}else{
						layer.msg(data.msg);
					}
				}
			})

		}
		
	    //JS实现新增规格
	    $(".addSpec").click(function(){
	    	$(this).parent().append('<br/><div><input type="text" class="areaShow" name="detailArea" /><input type="hidden"   name="AreaId" /><input type="text" name="firstNum" /><input type="text"  name="firstPrice" /><input type="text"  name="nextNum" /><input type="text"  name="nextPrice" /><button class="delSpec">删除规格</button></div>');
	    })
	    //JS实现删除规格
	    $("body").delegate(".delSpec",'click',function(){
	    	$(this).parent().prev().remove();
	    	$(this).parent().remove();
	    })
	    
	    function priceChange(){
	    	var a = $("#priceType").val();
	    	if(a==null || a=="")
	    		return;
	    	if(a=="1"){
	    		$("#specPriceNew").val("续件（个）");
	    		$("#specNum").val("首件（个）")
	    	}
	    	if(a=="2"){
	    		$("#specPriceNew").val("续重");
	    		$("#specNum").val("首重")
	    	}
	    }
	    
	    function typeChange(){
	    	var a = $("#formworkType").val();
	    	if(a=="2"){
	    		$("#priceTypediv").hide();
	    		$("#formworkdiv").hide();
	    	}
	    	if(a=="1"){
	    		$("#priceTypediv").show();
	    		$("#formworkdiv").show();
	    	}
	    }
	    
	    $("body").delegate(".areaShow",'click',function(){
	    	var a = $(this);
	    	var b = $(this).next();
	    	//取消所有选中状态
	    	var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	    	treeObj.checkAllNodes(false);
	    	treeObj.cancelSelectedNode();
	    	//地区回显数据
	    	var c = b[0].value;
	    	if(c!=null && c!=""){
	    		var d = c.split(";");
	    		var ids = [];
	            for (var i = 0; i < d.length; i++) {
	                ids.push(d[i]);
	            }
	            initMenuCheck(ids);
	    	}
			//弹窗显示地区
	    	layer.open({
	    		  type: 1,
	    		  skin: 'layui-layer-gray', //样式类名
	    		  title: ["选择地址","background:#1cb194;color:#fff;font-weight:bold"],
	    		  shadeClose: false,
		          scrollbar:false,
	    		  closeBtn: 0, //不显示关闭按钮
	    		  anim: 2,
	    		  area: ['420px', '520px'],
	    		  shadeClose: true, //开启遮罩关闭
	    		  content: $("#areaShow"),
	    		  btns: 2,
		            btn: ['确定','取消'],
		            yes: function(index){
		            	//获取选中的节点
		            	var ids = getCheckedMenuIds();
		            	var names = getCheckedMenuNames();
		            	var idss="";
		            	for(var i=0;i<ids.length;i++){
		            		idss+=";"+ids[i];
		            	}
		            	idss = idss.substring(1)
		            	b[0].value=idss;
		            	var namess="";
		            	for(var i=0;i<names.length;i++){
		            		namess+=";"+names[i];
		            	}
		            	namess = namess.substring(1)
		            	a[0].value=namess;
		                layer.close(index);
		            },
		            no: function(index){
		            	layer.close(index);
		            }
	    		});   	
	    })
		
	</script>
</body>
</html>